/**
 * @Author: panda
 * @Date: 2022-05-18 10:49
 * @Description: 用户pinia
 */
import {defineStore} from 'pinia';
import {store} from '@/store';
import {GetUserInfoModel, LoginParams, RegisterParams,} from '@/api/model/user';
import {userApi} from '@/api/user';
import localCache from "@/utils/localCache";
import {router} from '@/router';
import {ElMessageBox} from 'element-plus'
import {ElNotification} from "element-plus/es";

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  sessionTimeout?: boolean;
}

export interface UserInfo {
  id: string | number;
  username: string;
  avatar: string;
  detail?: string;
  sex: string
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: {
      id: '',
      username: '',
      sex: '',
      avatar: '',
      detail: '',
    },
    // token
    token: '',
    // Whether the login expired
    sessionTimeout: false
  }),
  getters: {
    getUserInfo(): UserInfo {
      return this.userInfo?.id ? this.userInfo : localCache.getCache('USER_INFO_');
    },
    getToken(): string {

      return this.token || localCache.getCache('token');
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    }
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      localCache.setCache('token', info)
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      localCache.setCache('USER_INFO_', info);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    resetState() {
      this.userInfo = null;
      this.token = '';
      // this.roleList = [];
      // this.sessionTimeout = false;
    },
    /**
     * @description: login
     */
    async login(params: LoginParams & { goHome?: boolean; },): Promise<GetUserInfoModel | null> {
      try {
        const {...loginParams} = params;
        return await userApi.userLogin({
          username: loginParams.username,
          passwordHash: loginParams.passwordHash
        }).then(
          res => {
            const {code, msg, data} = res.data;
            if (code === 200) {
              this.setUserInfo(data.userInfoVo)
              this.setToken(data.token);
              return this.getUserInfo;
            } else {
              ElNotification({
                title: '错误信息',
                message: msg,
                type: 'error',
              })
              return null
            }
          }
        );
      } catch (error) {
        console.log(error)
        return Promise.reject(error);
      }
    },
    /**
     * @description: register
     */
    async register(params: RegisterParams & { goHome?: boolean; }, captchaCode: string, captchaId: string) {
      try {
        // const {...registerParams} = params;
        return await userApi.userRegister({
          username: params.username,
          passwordHash: params.passwordHash,
          captchaCode: captchaCode,
          captchaId: captchaId
        }).then(res => {
          const {code, msg} = res.data
          if (code === 200) {
            ElMessageBox.alert(msg, '注册成功', {
              confirmButtonText: '好的',
            })
            return Promise.resolve(msg)
          } else {
            ElMessageBox.alert(msg, '错误信息', {
              confirmButtonText: '好的',
            })
            return Promise.reject(msg);
          }
        })
      } catch (error) {
        console.log(error)
        return Promise.reject(error);
      }
    },
    /**
     * @description: logout
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await userApi.logout({}).then(res => {
            console.log(res)
            this.setToken('');
            this.setSessionTimeout(false);
            this.setUserInfo(null);
            goLogin && router.push("/study");
          }).catch(err => {
            console.log(err)
          });
        } catch {
          console.log('注销Token失败');
        }
      }
    },
    /**
     * @description: updateUser
     */
    async updateUser(user: UserInfo) {
      return await userApi.updateUserInfo({
        avatar: user.avatar,
        detail: user.detail,
        sex: user.sex,
        username: user.username
      }).then(
        res => {
          const {data, code, msg} = res.data
          if (code == 200) {
            console.log(data)
            this.setUserInfo(data)
            ElNotification({
              title: '修改成功',
              message: msg,
              type: 'success',
            })
          } else {
            ElNotification({
              title: '修改失败',
              message: msg,
              type: 'error',
            })
            return
          }
        }
      )
    },

    /**
     * @description: updateUser
     */
    async updateUsername(user: UserInfo) {
      return await userApi.updateUsername({
        avatar: user.avatar,
        detail: user.detail,
        sex: user.sex,
        username: user.username
      }).then(
        res => {
          const {data, code, msg} = res.data
          if (code == 200) {
            console.log(data)
            this.setUserInfo(data)
            ElNotification({
              title: '修改成功',
              message: msg,
              type: 'success',
            })
          } else {
            ElNotification({
              title: '修改失败',
              message: msg,
              type: 'error',
            })
            return
          }
        }
      )
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      ElMessageBox.confirm(
        '退出登陆?',
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          await this.logout(true);
        })
        .catch(() => {

        })
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
